import tAlert from '#/components/Alert';
import { CloseCircleOutlined } from '#/utils/antdIcons';
import emitter from '#/utils/events.js';
import TRNotification from '#/utils/notification';
import { useSetState, useSize } from 'ahooks';
import { ConfigProvider, Drawer } from 'antd';
import zhCN from 'antd/es/locale/zh_CN';
import { useEffect, useRef } from 'react';
import { RENDER_STATE } from './helper';
import styles from './index.less';

interface IProps {
  drawerWidth?: number | string;
  originParams: object;
  onPress: (value?: any) => void;
  handleFreshTable?: () => void;
}

const DrawerHoc = (WarpComComponent) => {
  return function HOCComponent(props: IProps) {
    const { drawerWidth = '100%', originParams = {}, onPress, handleFreshTable } = props;
    const { title, propsButtonType = '', pageId = '' } = originParams;
    const mainRef = useRef(null);
    const drawerContentRef = useRef(null);
    const [state, setState] = useSetState({
      visible: false,
      loading: false,
      buttonLoading: false,
    });

    const mainSize = useSize(mainRef);

    useEffect(() => {
      setState({ visible: true });
    }, []);

    async function onDrawerClose(buttonType: string) {
      if (buttonType === 'requestBeforeBack' && pageId === 'yc8cNTm1jc623dik') {
        drawerContentRef.current.removeFile();
        return;
      }
      if (buttonType === 'back') {
        _onHandleClose();
        handleFreshTable && handleFreshTable();
        return;
      }
      if (originParams.renderState && RENDER_STATE.READ !== originParams.renderState) {
        if (buttonType === 'save') {
          _onHandleClose();
          if (originParams.renderState === RENDER_STATE.EDIT) {
            emitter.emit(RENDER_STATE.READ);
            return;
          }
          handleFreshTable && handleFreshTable();
          return;
        }
        const obj = await tAlert.show('当前工作将不被保存，继续执行此操作？');
        if (obj.index === 1) {
          _onHandleClose();
        }
      } else {
        _onHandleClose();
      }
    }

    function _onHandleClose() {
      setState({ visible: false });
      onPress({});
    }

    return (
      <Drawer
        visible={state.visible}
        width={drawerWidth}
        className={styles.drawer}
        destroyOnClose
        closable={false}
        maskClosable={false}
      >
        <ConfigProvider locale={zhCN}>
          <div className={styles.drawerContainer} ref={mainRef}>
            <div className={styles.drawerHeader}>
              <div className={styles.drawerHeader_left}>
                <span>{title.firstTitle}</span>
                {(title.twoTitle && (
                  <span style={{ color: '#fff', fontWeight: '500' }}>/{title.twoTitle}</span>
                )) ||
                  ''}
              </div>
              <CloseCircleOutlined
                onClick={() => onDrawerClose(propsButtonType)}
                style={{ fontSize: '20px', color: '#ACB1C1' }}
              />
            </div>
            <WarpComComponent
              {...props}
              onClose={onDrawerClose}
              mainSize={mainSize}
              ref={drawerContentRef}
            />
          </div>
        </ConfigProvider>
      </Drawer>
    );
  };
};

class DrawerRef {
  __key__ = '';
  show = (params, childComponent) => {
    return new Promise((resolve) => {
      this.__key__ = String(Date.now());
      const Child = DrawerHoc(childComponent);
      TRNotification.add({
        key: this.__key__,
        content: (
          <Child
            {...params}
            onPress={(result) => {
              TRNotification.remove(this.__key__);
              this.__key__ = '';
              resolve(result);
            }}
          />
        ),
        duration: null,
      });
    });
  };
  dismiss = (clear) => {
    if (clear) {
      TRNotification.clear();
    } else {
      TRNotification.remove(this.__key__);
    }
    this.__key__ = '';
  };
}

const drawer = new DrawerRef();
export default drawer;
